package com.mar.bt.server.impl;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import net.java.dev.marge.communication.CommunicationListener;

class BTInputStream extends InputStream implements CommunicationListener {

	private static final int DEFAULT_CAPACITY = 64;
	BlockingQueue<ByteBuffer> blockingQueue = new ArrayBlockingQueue<ByteBuffer>(DEFAULT_CAPACITY);
	private ByteBuffer currentInput = null;
	
	
	@Override
	public int read() throws IOException {
		if ( currentInput == null || !currentInput.hasRemaining() ){
			try {
				currentInput = blockingQueue.take();
			} catch (InterruptedException e) {
				e.printStackTrace();
				return -1;
			}
		}
		return currentInput.get();
	}

	public void errorOnReceiving(IOException arg0) {
		// TODO Auto-generated method stub
		arg0.printStackTrace();
	}

	public void errorOnSending(IOException arg0) {
		// TODO Auto-generated method stub
		arg0.printStackTrace();
	}

	public void receiveMessage(byte[] arg0) {
		try {
			blockingQueue.put( ByteBuffer.wrap(arg0));
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
